from multiprocessing import Process
import time
import allure
from eval_lib.common.logger import get_logger
from deploy.dfenvs import DFEnvs
from eval_lib.databases.redis.runner_info import RedisRunnerInfo
from eval_lib.databases.redis import const as redis_const

log = get_logger()


class DeployBase(Process):
    type = ""
    def __init__(self, uuid):
        super().__init__()
        self.uuid = uuid
        self._status = ""
        self.redis_runner = RedisRunnerInfo()
        self.redis_envs = DFEnvs(uuid)

    @property
    def status(self):
        return self._status

    @status.setter
    def status(self, new_status):
        self._status = new_status
        deploy_info = self.to_redis_envs_info()
        if new_status == "init":
            self.redis_envs.init(name=deploy_info["name"], type=deploy_info["type"])
        else:
            self.redis_envs.update(deploy_info.pop("name"), **deploy_info)

    def to_redis_envs_info(self):
        return {
            "name": "",
            "type": self.type,
        }

    def step(self, title):
        log.info(title)  # 记录步骤开始的日志
        while True:
            # 从Redis获取运行者信息
            sync_status = self.redis_runner.sync_case_status(uuid=self.uuid)
            if sync_status == redis_const.CASE_STATUS_CANCELLED:
                log.info("case cancel success")
                assert False
            # 如果同步后状态不是running，则每隔20秒检查一次；如果是，则结束循环
            if sync_status != redis_const.CASE_STATUS_RUNNING:
                time.sleep(20)
                log.info(f"stop execute case, wait 20s, ctrl-status is {sync_status}")
            else:
                break
        # 执行allure步骤，并返回结果
        return allure.step(title)